package com.platform.modules.order;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.Constant;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.JedisUtil;
import com.platform.common.utils.StringUtils;
import com.platform.modules.mall.entity.*;
import com.platform.modules.mall.service.MallGoodsService;
import com.platform.modules.mall.service.MallGoodsToActivityService;
import com.platform.modules.mall.service.MallOrderGoodsService;
import com.platform.modules.sys.service.SysConfigService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActivityOrderBuild extends AbsOrderBuild<BaseInitParams> {

    private SysConfigService sysConfigService;
    private JedisUtil jedisUtil;
    private MallGoodsToActivityService goodsToActivityService;
    private MallGoodsService goodsService;
    private MallOrderGoodsService orderGoodsService;

    public ActivityStatusResult activityStatus;
    protected MallGoodsEntity entity;

    public ActivityOrderBuild(SysConfigService sysConfigService,
                              JedisUtil jedisUtil,
                              MallGoodsToActivityService goodsToActivityService,
                              MallGoodsService goodsService,
                              MallOrderGoodsService orderGoodsService) {
        this.sysConfigService = sysConfigService;
        this.jedisUtil = jedisUtil;
        this.goodsToActivityService = goodsToActivityService;
        this.goodsService = goodsService;
        this.orderGoodsService = orderGoodsService;
    }

    @Override
    public void init(BaseInitParams initParams) {
        super.init(initParams);
        this.activityStatus = initParams.getActivityStatus();
        this.entity = initParams.getEntity();
    }

    @Override
    public void paramsVerify() {

    }

    @Override
    public void limited() {
        if(entity.getIsLimited() == null || entity.getIsLimited() < 1){
            return;
        }
        MallUserCardEntity userCardEntity = new MallUserCardEntity();
        userCardEntity.setUserId(user.getId());
        // 本次活动的开始时间
        userCardEntity.setAddTime(DateUtils.strToDate(activityStatus.getDate()[0].toString()));
        // 微信优惠标识不一样 限购也不一样
        userCardEntity.setCouponTag(entity.getGoodsTag());
        // 本次活动的ID
        userCardEntity.setActivityId(params.getActivityId());
        MallOrderEntity orderGoodsEntity = orderGoodsService.queryUserRecord(userCardEntity);
        if (orderGoodsEntity != null && orderGoodsEntity.getNumber() != null && orderGoodsEntity.getNumber() + params.getNumber() > entity.getIsLimited()) {
            if (orderGoodsEntity.getOrderStatus().equals(Constant.OrderStatus.DFK.getValue())) {
                throw new BusinessException("当前存在一次 " + activityStatus.getExtend1() + " 订单未支付，是否需要完成待支付订单?", 901);
            }
            Map<String, String> map = null;

            try {
                map = JSONObject.parseObject(sysConfigService.getValue("GOODS_TAG_DESC"), HashMap.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (map != null && StringUtils.isNotBlank(map.get(entity.getGoodsTag()))) {
                throw new BusinessException("非常抱歉，" + map.get(entity.getGoodsTag()) + "购买名额您已用完");
            }
            throw new BusinessException("非常抱歉，" + activityStatus.getExtend1() + "购买名额您已用完");
        }
    }

    @Override
    public void minusGoodsNumber() {
        if (!activityStatus.getIsStart()) {
            throw new BusinessException("不在活动时间！");
        }

        // redis库存扣减
        if (jedisUtil.hincrBy(Constant.ACTIVITY_DETAILS_STOCK + params.getActivityId(), activityStatus.getGoodsToActivityId(), -params.getNumber().longValue()) < 0) {
            // 数量置0  使其不出现负数
            jedisUtil.hincrBy(Constant.ACTIVITY_DETAILS_STOCK + params.getActivityId(), activityStatus.getGoodsToActivityId(), params.getNumber().longValue());
            throw new BusinessException("已经被抢完啦！下次再来吧");
        }
        // 减活动配置库存
        if (!goodsToActivityService.lambdaUpdate().setSql("expend_count = expend_count - " + params.getNumber())
                .eq(MallGoodsToActivityEntity::getId, activityStatus.getGoodsToActivityId()).ge(MallGoodsToActivityEntity::getExpendCount, params.getNumber())
                .update()) {
            throw new BusinessException("商品库存不足.");
        }
        goodsService.minusGoodsNumber(entity, params.getNumber());
    }

    @Override
    public MallOrderEntity orderInfo(MallGoodsEntity goods) {
        MallOrderEntity orderInfo = super.orderInfo(goods);
        orderInfo.setOrderType(Constant.CARD_ORDER);
        if (StringUtils.isBlank(orderInfo.getActivityType())) {
            orderInfo.setActivityType(activityStatus.getActivityTag());
        }
        return orderInfo;
    }

    @Override
    public List<MallOrderGoodsEntity> orderGoods() {
        return super.orderGoods(entity);
    }

    @Override
    public void saveAfter() {

    }

    @Override
    public void exceptionHandle() {
        // 全部库存充足的情况下出现异常需要进行 redis 库存回退
        jedisUtil.hincrBy(Constant.ACTIVITY_DETAILS_STOCK + params.getActivityId(), activityStatus.getGoodsToActivityId(), params.getNumber().longValue());
    }
}
